<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Model\Cat;

class CatController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
      $cat = Cat::all();
      $cat = $this->findTree($cat,0,0);
      return view('cat.index')->with('cat',$cat);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $cat = Cat::all();
        $cat = $this->findTree($cat,0,0);
        return view('cat.cat_add')->with('cat',$cat);
      
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        
       //$cat = cat::create($request->except('_token'));
        $cat = new cat();
        $cat->cat_name = $request->cat_name;
        $cat->pid = $request->pid;
        $cat->save();
        return redirect('/admin/cat');

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {

        $cat = Cat::all();
        $cat = $this->findTree($cat,0,0);
        return view('cat.cat_edit')->with('cat',$cat);

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }


    protected function findTree($data,$id=0,$lev=0)
    {
        static $tree=[];
        foreach($data as $k=>$v){
            if($v->pid==$id){
                $v->lev=$lev;
                $tree[] = $v;
                $this->findTree($data,$v->cat_id,$lev+1);
            }
        }
        return $tree;
    }


}
